package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.config.AlipayConfig;
import com.example.service.OrderService;
import com.example.service.PayService;
import com.example.service.PaymentInfoService;
import com.example.service.UserMessageService;
import com.example.vo.AliPay;
import com.example.vo.AliPaySync;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@Service
public class PayServiceImpl implements PayService {
    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private PaymentInfoService paymentInfoService;



    @Autowired
    private OrderService orderService;


    @Resource
    private UserMessageService userMessageService;


    @Override
    public String aliPay(AliPay alipay) throws AlipayApiException {
        // 1、获得初始化的AlipayClient
        String serverUrl = alipayConfig.getGatewayUrl();
        String appId = alipayConfig.getAppId();
        String privateKey = alipayConfig.getPrivateKey();
        String format = "json";
        String charset = alipayConfig.getCharset();
        String alipayPublicKey = alipayConfig.getPublicKey();
        String signType = alipayConfig.getSignType();
        String returnUrl = alipayConfig.getReturnUrl();
        String notifyUrl = alipayConfig.getNotifyUrl();
        //System.out.println(appId);
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
        // 2、设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 页面跳转同步通知页面路径
        alipayRequest.setReturnUrl(returnUrl);
        // 服务器异步通知页面路径
        alipayRequest.setNotifyUrl(notifyUrl);
        // 封装参数
        alipayRequest.setBizContent(JSON.toJSONString(alipay));
        // 3、请求支付宝进行付款，并获取支付结果

        String result = alipayClient.pageExecute(alipayRequest).getBody();
        // 返回付款信息
        //创建订单
        paymentInfoService.insert(alipay);
        return result;

    }

    @Override
    public String AliPayAsyncHandle(AliPaySync aliPaySync, HttpServletRequest request) throws AlipayApiException {

        Map<String,String> params = new HashMap<String, String>();

        Map<String,String[]> requestMap = request.getParameterMap();

        Set<String> set = requestMap.keySet();

        Iterator<String> it = set.iterator();

        while(it.hasNext()){
            String name = it.next();
            String[] values = requestMap.get(name);
            String str = "";
            for(int i= 0;i<values.length;i++){
                if (i < values.length - 1){
                    str+=values[i]+",";
                }else{
                    str+=values[i];
                }
            }
            params.put(name,str);
        }

        //签名验证
        Boolean signVerified = AlipaySignature.
                rsaCheckV1(params,
                        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvF216deBSyJlprYq20WoEG7aKU8SIhqIco3jHjnO5lzb5cJSM/LiRS6VEVkpjCjS8Bx2lJHG8474z4TFzfM3ITHJZc8+iPEZHNmn+LG8Vqi76PzwmNNILLMXaAbvm+TLn3FLumH5o/JRvSwtKcBLT/6y7JHwBb8hhIgU27wAlXqxI4GmbFRm87PR7CVVZgslOrFr72KkasL5v0ujwHOxGyas4v9lFwT3rc6g0NNAez13vFY8LWUZZZXOcWTJODnupFyYQPWZTG+Ch8NZZO96RidbmR01D2u6YRKjfHM6yWBEJQ4JRZyoVhqmhJu6QR10nDoxutUXgzz5K0mApzl8YwIDAQAB",
                        "UTF-8",
                        "RSA2");


        if (signVerified){
            //判断支付结果
            if (aliPaySync.getTrade_status().equals("TRADE_SUCCESS") || aliPaySync.getTrade_status().equals("TRADE_FINISH")){

                System.out.println("订单号:"+aliPaySync.getOut_trade_no());
                //修改订单状态 未支付-->已支付
                orderService.updateOrderStatus(aliPaySync.getOut_trade_no());
                orderService.updataUserIntegration(aliPaySync.getOut_trade_no());
                // 更新支付信息
                paymentInfoService.updatePaymentInfo(aliPaySync);

            }else if ("TRADE_CLOSED".equals(aliPaySync.getTrade_status())) {
                System.out.println("订单号:"+aliPaySync.getOut_trade_no()+"已取消");
                // 订单已关闭，用户取消支付
                orderService.handlePaymentCancellation(aliPaySync.getOut_trade_no());
            } else{
                return "error";
            }
            return "success";
        }else{
            System.out.println("签名验证未通过");
            return "error";
        }
    }
}
